package cn.net.mugui.jsonbean.strengthen;

import com.alibaba.fastjson.JSONArray;
import com.mugui.bean.JsonBean;

import java.util.*;

public class JsonBeanUtil {

	public static  <T extends JsonBean> List<T> parseArray(String data, Class<T> channelGoodsReqClass) {
		return parseArray(JSONArray.parseArray(data),channelGoodsReqClass);
	}
	public static <T extends JsonBean> List<T> parseArray(JSONArray data, Class<T> channelGoodsReqClass) {
		LinkedList<T> list=new LinkedList<>();
		Iterator<Object> iterator = data.iterator();
		while(iterator.hasNext()){
			list.add(T.newBean(channelGoodsReqClass,iterator.next()));
		}
		return list;

	}

	/**
	 * 得到隐式传递的json数据
	 * @param reqs
	 */
	public static <T extends List<? extends  JsonBean>> JSONArray getImplicitJson(T reqs) {
		JSONArray array=new JSONArray();
		reqs.forEach(key->array.add(key.get()));
		return array;
	}

	/**
	 * 字段中 <br>
	 * list或map类型修复
	 * @param req
	 */
	public static <T extends JsonBean,R extends JsonBean> void fieldTypeRepair(T req,String fieldName,Class<R> fieldClass) {
		Object o = req.get(fieldName);
		if(o instanceof Map){
			Iterator<? extends Map.Entry<?, ?>> iterator = ((Map<?, ?>) o).entrySet().iterator();
			while(iterator.hasNext()){
				Map.Entry next = iterator.next();
				R r = JsonBean.newBean(fieldClass, next.getValue());
				next.setValue(r);
			}
		}else if(o instanceof Collection){
			Iterator<?> iterator = ((Collection<?>) o).iterator();
			JSONArray array=new JSONArray();
			while(iterator.hasNext()){
				Object next = iterator.next();
				array.add(JsonBean.newBean(fieldClass,next));
			}
			req.set(fieldName,array);
		}
	}
}
